package com.flight.trans.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.flight.trans.R;
import com.flight.trans.adapter.EnterPortPickingDetailsAdapter;
import com.flight.trans.base.BaseActivity;
import com.flight.trans.bean.EnterPickingBean;
import com.flight.trans.bean.EnterPortStorageBean;
import com.flight.trans.bean.EnterPortTakeBean.EnterPortTakeData;
import com.flight.trans.bean.EnterPortTakeDetailBean.EnterPortTakeDetailData;
import com.flight.trans.global.Constant;
import com.flight.trans.global.ConstantInfo;
import com.flight.trans.http.NetworkUtils;
import com.flight.trans.http.network.OkGoBackListener;
import com.flight.trans.listener.OnItemClickListener;
import com.flight.trans.listener.OnTextClickListener;
import com.flight.trans.util.CommonUtils;
import com.flight.trans.util.JsonUtils;
import com.flight.trans.util.ToastUtils;
import com.flight.trans.view.dialog.AlertDialog;
import com.flight.trans.view.dialog.StorageContainerDialog;
import com.flight.trans.view.edit.EditorActivity;
import com.lzy.okgo.model.HttpParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 进港出库
 */
public class EnterPortPickingDetailsActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mLlContainer ;
    private TextView mTvTitleName;
    private RecyclerView mRvContainer ;

    private Button mBtnPickingConfirm ;//事故签字

    private TextView mTvTakeNo ,//提货单号
            mTvCreatePerson ;//开单人

    private ImageView mIvSelected ;// 全部选择

    private EnterPortTakeData mTakeData ;
    private EnterPortPickingDetailsAdapter mPickingDetailsAdapter;
    private List<EnterPortTakeDetailData> mTakeDetailDataList ;

    @Override
    protected int setContentView() {
        return R.layout.activity_enter_port_picking_details;
    }

    @Override
    protected void initView() {
        mLlContainer = findViewById(R.id.mLlContainer);
        mTvTitleName = findViewById(R.id.mTvTitleName);
        mRvContainer = findViewById(R.id.mRvContainer);

        mBtnPickingConfirm = findViewById(R.id.mBtnPickingConfirm);

        mIvSelected = findViewById(R.id.mIvSelected);

        mTvTakeNo = findViewById(R.id.mTvTakeNo);
        mTvCreatePerson = findViewById(R.id.mTvCreatePerson);
    }

    @Override
    protected void initData() {
        mTakeData = (EnterPortTakeData) mBundle.getSerializable(Constant.INFO);
        IsEditor = mBundle.getBoolean(Constant.IsEditor);

        ConstantInfo.UnusualIDList.clear();

        mTvTakeNo.setText(mTakeData.getConsigneeNo());
        mTvCreatePerson.setText(mTakeData.getConsigneeCreateByName());

        mTvTitleName.setText(getString(R.string.title_enter_port_picking_goods_details));
        CommonUtils.onFinishTouch(mActivity , mLlContainer);
    }

    @Override
    protected void initConnect() {
        linked(true);
    }

    private void linked(boolean isFirst){
        valueParams = new HttpParams();
        valueParams.put(Constant.Consignee_No , mTakeData.getConsigneeNo());

        NetworkUtils.getEnterPortPickingDetails(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {

                if(isFirst) {
                    mTakeDetailDataList = (List<EnterPortTakeDetailData>) body;

                    if(mTakeDetailDataList == null)
                        mTakeDetailDataList = new ArrayList<>();

                    for (int i = 0; i < mTakeDetailDataList.size(); i++)
                        mTakeDetailDataList.get(i).setSelected(mTakeDetailDataList.get(i).getState() != Constant.Be_Picking);
                }else {
                    List<EnterPortTakeDetailData> mDataList = (List<EnterPortTakeDetailData>) body;
                    Map<String , EnterPortTakeDetailData> mDataMap = new HashMap<>();

                    for (int i = 0; i < mDataList.size(); i++) {
                        mDataMap.put(mDataList.get(i).getOrderNo() , mDataList.get(i));
                    }

                    for (int i = 0; i < mTakeDetailDataList.size(); i++) {
                        mTakeDetailDataList.get(i).setInwardStorageDetailData(mDataMap.get(mTakeDetailDataList.get(i).getOrderNo()).getInwardStorageDetailData());
                        mTakeDetailDataList.get(i).setAnomalyCnt(mDataMap.get(mTakeDetailDataList.get(i).getOrderNo()).getAnomalyCnt());
                    }
                }

                initAdapter();
                initLocationButton();
                // 初始化选择
                initSelected(getSelected());
            }
        }, valueParams);
    }

    private void initAdapter(){
        if(mPickingDetailsAdapter == null) {
            mPickingDetailsAdapter = new EnterPortPickingDetailsAdapter(mActivity, mTakeDetailDataList);
            mRvContainer.setAdapter(mPickingDetailsAdapter);
            mRvContainer.setLayoutManager(new LinearLayoutManager(mActivity));

            mPickingDetailsAdapter.setOnItemClickListener(new TakeItemClickListener());
            mPickingDetailsAdapter.setOnTextClickListener(new TakeItemTextClickTextListener());
        }else {
            mPickingDetailsAdapter.updateAdapter(mTakeDetailDataList);
        }
    }

    private void initLocationButton(){
        mBtnPickingConfirm.setVisibility(IsEditor ? View.VISIBLE : View.GONE);

        if(IsEditor)
            mIvSelected.setOnClickListener(this);
    }

    /**
     * 条目字段点击事件
     */
    private class TakeItemTextClickTextListener implements OnTextClickListener {
        @Override
        public void onClick(View view, int position) {
            switch (view.getId()){
                case R.id.mTvPickingCount:
                    // 出库件数
                    EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mTakeDetailDataList.get(position).setOutboundNumber(Integer.parseInt(content));

                            initAdapter();
                        }
                    } , String.valueOf(mTakeDetailDataList.get(position).getOutboundNumber()));
                    break;
                case R.id.mTvStorageArea:
                    // 存放区域
                    StorageContainerDialog.getInstance(mActivity)
                            .setContent(mTakeDetailDataList.get(position).getInwardStorageDetailData() , IsEditor)
                            .setConfirmButton(new StorageContainerDialog.OnConfirmClickListener() {
                                @Override
                                public void onClick(List<EnterPortStorageBean> contentList) {
                                    mTakeDetailDataList.get(position).setInwardStorageDetailData(contentList);
                                }
                            })
                            .show();
                    break;
                case R.id.mTvUnusualStatus:
                    // 存放区域
                    mIntent = new Intent(mActivity , UnusualListActivity.class);
                    mBundle = new Bundle();
                    mBundle.putBoolean(Constant.IsEditor , IsEditor);
                    mBundle.putInt(Constant.Business_ID , mTakeDetailDataList.get(position).getInwardOrderId());
                    mBundle.putString(Constant.Key_Order_No , mTakeDetailDataList.get(position).getOrderNo());
                    mBundle.putInt(Constant.Source_Type , 5);
                    mIntent.putExtras(mBundle);
                    turnActForResult(mIntent);
                    break;
                case R.id.mTvOrderNo:
                    // 运单号
                    ToastUtils.showToast(mTakeDetailDataList.get(position).getOrderCreateTime());
                    break;
            }
        }
    }

    /**
     * 条目点击事件
     */
    private class TakeItemClickListener extends OnItemClickListener {
        @Override
        public void onClick(View view, int position) {
            mTakeDetailDataList.get(position).setSelected(!mTakeDetailDataList.get(position).isSelected());

            initAdapter();

            // 初始化选择
            initSelected(getSelected());
        }
    }

    @Override
    public void onClick(View v) {
        if(CommonUtils.isFastDoubleClick())
            return;

        switch (v.getId()){
            case R.id.mIbBack:
                onBackPressed();
                break;
            case R.id.mIvSelected:
                // 全选
                if(!IsEditor)
                    return;

                if(mTakeDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                boolean selected = getSelected();
                for (int i = 0; i < mTakeDetailDataList.size(); i++) {
                    mTakeDetailDataList.get(i).setSelected(!selected);
                }
                initAdapter();
                initSelected(!selected);
                break;
            case R.id.mBtnPickingConfirm:
                // 确认出库
                if(mTakeDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                showConfirmPickingGoodsDialog();
                break;

        }
    }

    /**
     * 全选、全取消
     * @param isSelected
     */
    private void initSelected(boolean isSelected){
        mIvSelected.setImageDrawable(mActivity.getDrawable(isSelected ? R.mipmap.check_item_sel :R.mipmap.check_item_blue));
    }

    /**
     * 点击提货确认
     */
    private void showConfirmPickingGoodsDialog(){
            if (getSelectedItem().size() != 0) {
                if (getSelectedItem().size() != mTakeDetailDataList.size()) {
                    // 非全部出库
                    ToastUtils.showToast(R.string.toast_picking_not_all);
                } else {
                    //全部出库
                    showConfirmDialog(R.string.dialog_confirm_picking);
                }
            }else{
                ToastUtils.showToast(R.string.toast_please_select_order);
            }
    }

    private void showConfirmDialog(int content){
        if(IsSaveIng){
            ToastUtils.showToast(R.string.toast_save_ing);
            return;
        }

        AlertDialog.getInstance(mActivity)
                .setContent(content)
                .setConfirmButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        List<EnterPickingBean> list = new ArrayList<>();

                        for (int i = 0; i < mTakeDetailDataList.size(); i++) {
                            list.add(new EnterPickingBean(mTakeDetailDataList.get(i).getInwardOrderDetailId() ,mTakeDetailDataList.get(i).getOutboundNumber()));
                        }

                        IsSaveIng = true ;
                        NetworkUtils.saveEnterPortPickingDetails(new OkGoBackListener(mActivity) {
                            @Override
                            public void onSuccess(Object body) {
                                IsSaveIng = false;
                                ToastUtils.showToast(R.string.toast_submit_success);
                                onFinish(Constant.RESULT_CODE);
                            }

                            @Override
                            public void onError() {
                                IsSaveIng = false;
                            }
                        }, JsonUtils.parseBeanToJson(list));
                    }
                }).show();
    }


    /**
     * 获取选择的运单
     * @return
     */
    private List<Integer> getSelectedItem(){
        List<Integer> integerList = new ArrayList<>();
        for (int i = 0; i < mTakeDetailDataList.size(); i++) {
            if(mTakeDetailDataList.get(i).isSelected() || mTakeDetailDataList.get(i).getState() != Constant.Be_Picking){
                integerList.add(mTakeDetailDataList.get(i).getInwardOrderDetailId());
            }
        }
        return integerList;
    }


    /**
     * 判断是否全部选中
     * @return
     */
    private boolean getSelected(){
        boolean isSelected = true ;
        for (int i = 0; i < mTakeDetailDataList.size(); i++) {
            if(!mTakeDetailDataList.get(i).isSelected()){
                isSelected = false ;
                break;
            }
        }
        return isSelected;
    }

    @Override
    protected void initRefresh(int count) {
        super.initRefresh(count);

        NetworkUtils.checkPageLock(new OkGoBackListener(mActivity) , ConstantInfo.IN_PICKING , mTakeData.getConsigneeNo());
    }
}
